import { getToken } from '~/utils/auth'
let baseURL = process.env.NODE_ENV === 'development' ? '/dev-api' : '/prod-api'
if (process.server) {
  baseURL = `http://${process.env.HOST || 'localhost'}:${process.env.PORT || 3000}${baseURL}`
}

/**
 * 失败回调
 * @param error
 * @returns {Promise<never>}
 */
const onRejected = (error) => {
  console.error('err' + error)
  return Promise.reject(error)
}

export var request = {}

export default ({ store, app, redirect, $axios, route, req }) => {
  // request
  $axios.interceptors.request.use(
    (config) => {
      const { user, app } = store.state
      $axios.setHeader('Content-Type', 'application/json;charset=utf-8')
      const token = getToken() ? getToken() : user.token
      if (token) {
        $axios.setToken(token, 'Bearer')
      }
      config.url += config.url.includes('?') ? '&r=' + new Date().getTime() : '?r=' + new Date().getTime()
      config.url = baseURL + config.url
      return config
    }, (error) => {
      console.log(error)
      Promise.reject(error)
    })
  // response
  $axios.interceptors.response.use((resp) => {
    const code = resp.data.code
    if (code === 401) {
      if (process.client) {
        store.dispatch('user/FedLogOut')
      }
      if (process.server) {
        redirect(`/login`)
      }
      return Promise.reject(resp.data)
    } else if (code !== 200) {
      console.error(resp.data.msg)
      return Promise.reject(resp.data)
    } else {
      return resp.data
    }
  }, onRejected)
  request = $axios
}
